import { queryHotRank } from '@/services/api/api-tophub-hotrank';
import { PlusOutlined } from '@ant-design/icons';
import { ActionType, DrawerForm, ProFormInstance, ProTable } from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { Alert, Button, message, Space, Table } from 'antd';
import Search from 'antd/lib/input/Search';
import React, { useRef, useState } from 'react';
import AddOperateAssociation from './AddOperateAssociation';
import AddOperateCreate from './AddOperateCreate';
interface AddOperateProps {
  onRefurbish: () => void;
}

const AddOperate: React.FC<AddOperateProps> = ({ onRefurbish }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  const [queryHotName, setQueryHotNameState] = useState<string>();

  const [selectHotQuerys, setSelectHotQueryState] = useState<TophubHotRankData.HotQuery[]>([]);

  const [open, setOpenState] = useState<boolean>(false);

  return (
    <DrawerForm
      title="补录热搜热榜"
      trigger={
        <Button type="primary">
          <PlusOutlined />
          补录热搜热榜
        </Button>
      }
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
        width: 900,
        extra: (
          <Space>
            <AddOperateCreate onRefurbish={function (): void {}} />
          </Space>
        ),
      }}
      formRef={formRef}
      open={open}
      onOpenChange={async (visible) => {
        setOpenState(visible);
        if (visible) {
        } else {
          setQueryHotNameState('');
          setSelectHotQueryState([]);
        }
      }}
      onValuesChange={(values) => {}}
      submitter={
        selectHotQuerys.length > 0
          ? {
              searchConfig: {
                resetText: <>关闭</>,
              },
              submitButtonProps: {
                hidden: true,
              },
              resetButtonProps: {
                type: 'primary',
                danger: true,
              },
              onReset(value) {},
              render: (props, defaultDoms) => {
                return [
                  defaultDoms,
                  <AddOperateAssociation
                    selectHotQuerys={selectHotQuerys}
                    onRefurbish={function (): void {}}
                    onOpenChange={function (visible: boolean): void {
                      if (visible) {
                      } else {
                        setOpenState(false);
                        //关闭
                        setQueryHotNameState('');
                        setSelectHotQueryState([]);
                        onRefurbish();
                      }
                    }}
                  />,
                ];
              },
            }
          : false
      }
      onFinish={async (values) => {
        console.log(values);
      }}
    >
      <>
        <Alert
          message="请输入热点词条进行查询（查询范围为30天内），进行关联操作。如没有查询到结果可点击右上方新建进行后续操作。"
          type="warning"
          showIcon
        />
        <Search
          style={{
            marginTop: '15px',
          }}
          placeholder="输入热点词条"
          allowClear
          enterButton="搜索"
          onSearch={(value) => {
            if (!value) {
              message.warning('请输入热点词条进行匹配查询');
              return;
            }
            setQueryHotNameState(value);
            actionRef.current?.reloadAndRest();
          }}
        />

        <ProTable<TophubHotRankData.HotQuery>
          columns={[
            {
              title: (
                <span
                  style={{
                    color: '#99a3b7',
                    fontSize: 12,
                    textAlign: 'center',
                    fontWeight: 'normal',
                  }}
                >
                  热点
                </span>
              ),
              dataIndex: 'name',
              align: 'center',
              copyable: true,
              ellipsis: true,
              width: '45%',
              render: (dom, entity, index, action) => <>{entity.name}</>,
            },
            {
              title: (
                <span
                  style={{
                    color: '#99a3b7',
                    fontSize: 12,
                    textAlign: 'center',
                    fontWeight: 'normal',
                  }}
                >
                  排名
                </span>
              ),
              dataIndex: 'topIndex',
              align: 'center',
            },
            {
              title: (
                <span
                  style={{
                    color: '#99a3b7',
                    fontSize: 12,
                    textAlign: 'center',
                    fontWeight: 'normal',
                  }}
                >
                  渠道
                </span>
              ),
              dataIndex: 'type',
              align: 'center',
              valueEnum: {
                1: { text: '微博' },
                2: { text: '抖音' },
                4: { text: '今日头条' },
              },
            },
            {
              title: (
                <span
                  style={{
                    color: '#99a3b7',
                    fontSize: 12,
                    textAlign: 'center',
                    fontWeight: 'normal',
                  }}
                >
                  范围
                </span>
              ),
              dataIndex: 'isCity',
              align: 'center',
              valueEnum: {
                0: { text: '全国' },
                1: { text: '重庆' },
              },
            },
            {
              title: (
                <span
                  style={{
                    color: '#99a3b7',
                    fontSize: 12,
                    textAlign: 'center',
                    fontWeight: 'normal',
                  }}
                >
                  媒体
                </span>
              ),
              dataIndex: 'author',
              align: 'center',
              render: (dom, entity, index, action) => entity.author,
            },
          ]}
          style={{
            marginTop: 25,
          }}
          actionRef={actionRef}
          rowKey="id"
          // polling={2000}
          dateFormatter="id"
          defaultSize={'small'}
          search={false}
          options={false}
          pagination={false}
          ghost
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          }}
          tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
            setSelectHotQueryState(selectedRows);
            return (
              <Space size={24}>
                <span>已选 {selectedRowKeys.length} 项</span>
                {selectedRows.filter((item) => item.isCity == 0).length > 0 && (
                  <span>{`全国: ${selectedRows.filter((item) => item.isCity == 0).length}项`}</span>
                )}
                {selectedRows.filter((item) => item.isCity == 1).length > 0 && (
                  <span>{`重庆: ${selectedRows.filter((item) => item.isCity == 1).length}项`}</span>
                )}
                {selectedRows.filter((item) => item.type == 1).length > 0 && (
                  <span>{`微博: ${selectedRows.filter((item) => item.type == 1).length}项`}</span>
                )}
                {selectedRows.filter((item) => item.type == 2).length > 0 && (
                  <span>{`抖音: ${selectedRows.filter((item) => item.type == 2).length}项`}</span>
                )}
                {selectedRows.filter((item) => item.type == 4).length > 0 && (
                  <span>{`今日头条: ${
                    selectedRows.filter((item) => item.type == 4).length
                  }项`}</span>
                )}
              </Space>
            );
          }}
          request={async () => {
            if (queryHotName) {
              const response = await queryHotRank({
                hotType: 1,
                hotIsCity: 0,
                hotName: queryHotName,
              });
              return Promise.resolve({
                data: response.data,
                total: response.data.length,
                success: response.code === 0,
              });
            } else {
              return Promise.resolve({
                data: [],
                total: 0,
                success: false,
              });
            }
          }}
        />
      </>
    </DrawerForm>
  );
};
export default AddOperate;
